#include "GLConsole.h"


namespace mp_gl
{


	template <class T>
	GLConsoleX<T>::GLConsoleX()
		: StringCollection(), Updateable(), LockableMutex()
	{
		
	}

	template <class T>
	GLConsoleX<T>::~GLConsoleX()
	{
		
	}


	template <class T>
	void GLConsoleX<T>::SendEvent(const T evnt)
	{
		while (!TryLock()){ mp_base::Delay(1); }

		//Send event to console
		WriteToConsole(evnt);
		//Send event to handlers
		SendEventsToHandlers(evnt);

		Unlock();
	}

	template <class T>
	void GLConsoleX<T>::SendEventsToHandlers(const T evnt)
	{
		if (m_handlers.size() > 0)
			for (EventHandlers<T>::iterator i = m_handlers.begin();
				i < m_handlers.end();
				i++)
			{
				(**i)(evnt);
			}
	}

	template <class T>
	void GLConsoleX<T>::RemoveHandler(EventHandler handler)
	{
		while (!TryLock()){ mp_base::Delay(1); }

		if (m_handlers.size() > 0)
		for (EventHandlers::iterator i = m_handlers.begin();
			i < m_handlers.end(); i++)
		{
			if (handler == *i)
			{
				m_handlers.erase(i);
				return;
			}
		}

		Unlock();
	}

	template <class T>
	void GLConsoleX<T>::FillStringBuffer(
		string* const buffer, const uint maxStrings)
	{
		while (!TryLock()){ mp_base::Delay(1); }

		if (m_collection.size() > 0)
		{
			uint stringCnt = 0;
			for (vector<string>::iterator i = m_collection.end();
				i > m_collection.begin(); i--)
			{
				buffer[stringCnt++] = *i;
				if (stringCnt >= maxStrings){ break; }
			}
		}

		Unlock();
	}

	template <class T>
	void GLConsoleX<T>::Update()
	{
		//

	}

}